<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;

class ShopGoods extends CommonModel {
	protected $table = 'shop_goods';

    // 只查询上架的
    public function scopeSales($query){
        $query->where('status','=',1)->where('start_time','<',date('Y-m-d H:i:s'));
    }
    public function scopeField($query){
        $query->select('shop_goods.id','shop_goods.goods_name','goods_price','goods_image','market_price','stock','end_time as time','status','cate_id','goods_type');
    }
    public function scopeList($query){
        $return=$query->pages();
        return $return;
    }
    //商品详情
    public function getGoodsDetail($goods_id){
        $goods_detail=self::select('id','store_id','goods_name','goods_type','goods_price','goods_image','goods_spec', 'summary','market_price','stock','start_time','end_time','start_type','end_type','status')->where(['id'=>$goods_id])->first();
        return $goods_detail;
    }

    //检测商品库存
    public function checkCart($goods_list){
        $right_detail="/\w+=*+:\w+=*+/";
        if(!preg_match($right_detail,$goods_list)){
            return ['msg'=>'参数错误！','status'=>0];
        }

        $right_detail="/(id=[0-9]*)/";
        if(!preg_match($right_detail,$goods_list)){
            return ['msg'=>'参数错误！','status'=>0];
        }

        $right_detail="/(num=[0-9]*)/";
        if(!preg_match($right_detail,$goods_list)){
            return ['msg'=>'参数错误！','status'=>0];
        }
        $goods_list = self::getGoodsAttr($goods_list);
        $goods_stock_ids = array();
        foreach ($goods_list as $key=>$val) {
            $goods_id=$val['goods_id'];
            $goods_number=$val['goods_number'];
            $data = self::getGoodsDetail($goods_id);
            //库存判断
            if($data->stock<$goods_number){
                $array=array(
                    'goods_id'=>$val['goods_id'],
                    'goods_number'=>$val['goods_number'],
                    'goods_stock'=>$val['goods_stock'],
                );
                $goods_stock_ids[]=$array;
            }
        }
        return ['status'=>1,'data'=>$goods_stock_ids];
    }
    //检测商品状态

    /**
     * $goods_list='id=5:num=6,id=6:num=8';
     * @param $goods_list
     * @param $village_id
     * @return array
     */
    public function checkGoodsStatus($goods_list,$village_id){
        $right_detail="/\w+=*+:\w+=*+/";
        if(!preg_match($right_detail,$goods_list)){
            return ['msg'=>'参数错误！','status'=>0];
        }

        $right_detail="/(id=[0-9]*)/";
        if(!preg_match($right_detail,$goods_list)){
            return ['msg'=>'参数错误！','status'=>0];
        }

        $right_detail="/(num=[0-9]*)/";
        if(!preg_match($right_detail,$goods_list)){
            return ['msg'=>'参数错误！','status'=>0];
        }

        $goods_list =self::getGoodsAttr($goods_list);
        $goods_id=$goods_list['0']['goods_id'];
        $goods_first_info = self::where('id',$goods_id)->select('store_id','goods_type')->first();
        $store_id = $goods_first_info->store_id;
        $order_type = $goods_first_info->goods_type;
        $store_info = ShopStore::getStoreDetailById($store_id);

        $village_array = explode(',',$store_info->village_ids);

        if(is_array($village_array)) {
            if (!in_array($village_id, $village_array))
                return ['msg' => '暂不支持配送该区域', 'status' => 0];
        }else{
            if($village_id!=$village_array)
                return ['msg' => '暂不支持配送该区域', 'status' => 0];
        }
        $work_start_time=date('H:i',strtotime($store_info->work_start_time));
        $work_end_time=date('H:i',strtotime($store_info->work_end_time));
        if($store_info->is_open!=1 || date('H:i')<$work_start_time || date('H:i')>$work_end_time){
            return ['msg'=>'店铺暂时关闭，营业时间:'.$work_start_time.'-'.$work_end_time,'status'=>0];
        }
        $store_detail =$store_info;

        $all_number = 0;
        $all_price = 0;

        foreach ($goods_list as $key=>$val){
            $goods_id=$val['goods_id'];
            $goods_number=$val['goods_number'];
            $data = self::getGoodsDetail($goods_id);

            //库存判断
            if($data->stock<$goods_number){
                return ['msg'=>'库存不足','goods_id'=>$val['goods_id'],'status'=>0];
            }
            $data->send_time = $store_info->send_time;

            if($data->status!=1){
                return ['msg'=>'商品已下架','goods_id'=>$val['goods_id'],'status'=>0];
            }
            if($data->end_type==2 && date('Y-m-d H:i:s')>$data->end_time){
                return ['msg'=>'商品已下架','goods_id'=>$val['goods_id'],'status'=>0];
            }

            unset($data->stock);
            unset($data->market_price);
            unset($data->summary);
            unset($data->start_time);
            unset($data->end_time);
            unset($data->start_type);
            unset($data->end_type);

            $data->goods_number = $val['goods_number'];
            $all_number += $goods_number;
            $all_price = bcadd (bcmul($goods_number,$data->goods_price,2),$all_price,2);//总价
            $store_detail->goods_list[$key] = $data;

        }

        $store_detail->all_number = $all_number;
        $store_detail->all_price = $all_price;
        if($all_price<$store_info->start_amount){
            return ['msg'=>'店铺起送价为'.$store_info->start_amount.'元，请再买一点东西吧','status'=>0];
        }
        $return['store_list'][] =$store_detail;
        $return['shipping_amount'] = $store_info->shipping_amount;
        $return['goods_all_price'] = $all_price;
        $return['all_price'] = bcadd($all_price,$store_info->shipping_amount,2);
        $return['order_type'] = $order_type;
        return ['msg'=>'OK','status'=>1,'data'=>$return];
    }
    //下订单减少库存
    public function updatedGoodsStock($goods_id,$goods_number){
        ShopGoodsStock::addSaleNumber($goods_id,0,$goods_number);
        return self::where(['id'=>$goods_id])->decrement('stock',$goods_number);
    }
    //取消订单增加库存
    public function rbackGoodsStock($goods_id,$goods_number){
        ShopGoodsStock::delSaleNumber($goods_id,0,$goods_number);
        return self::where(['id'=>$goods_id])->increment('stock',$goods_number);
    }

    //解析goods_attr
    public function getGoodsAttr($goods_list){

        $returnArr=array();
        $goods_info=explode(',',$goods_list);//分割字符串;

        foreach($goods_info as $key=>$val){

            $val=trim($val,"\"");
            $goods_row=explode(':',$val);

            $right=0;
            foreach($goods_row as $v){

                $goods_id_row=explode('=',$v);

                if($goods_id_row[0]=='id' && is_numeric($goods_id_row[1])){
                    $returnArr[$key]['goods_id']= intval(trim($goods_id_row[1]));
                    $right ++;

                }elseif($goods_id_row[0]=='num' && is_numeric($goods_id_row[1]) ){
                    $returnArr[$key]['goods_number']=intval(trim($goods_id_row[1]));
                    $right ++;
                }
            }

            if($right!=2){
                return "";
            }

        }
        return $returnArr;

    }
}